package com.phkj.qdh.ui.fragment.mynotice

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.databinding.FragmentMyLawNoticeDetailBinding
import com.phkj.qdh.databinding.FragmentMyTeamNoticeDetailBinding
import com.phkj.qdh.ui.adapter.FileTitleAdapter
import com.phkj.qdh.ui.adapter.ImagerViewAdapter
import com.phkj.qdh.ui.dialog.CommonConfirmDialog
import com.phkj.qdh.ui.dialog.CommonConfirmListener
import com.phkj.qdh.ui.fragment.user.UserVM
import com.phkj.qdh.ui.fragment.user.getUserVMProvider
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.gone
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import kotlinx.coroutines.flow.collectLatest
import java.util.HashMap

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 *
 */
class MyLawNoticeDetailFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: Int? = null
    private var param2: String? = null
    private var _binding: FragmentMyLawNoticeDetailBinding? = null
    private val binding get() = _binding!!
    private val iVAdapter by lazy { ImagerViewAdapter(true) }
    private lateinit var vm: UserVM
    private val fileTitleAdapter by lazy { FileTitleAdapter() }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getInt(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }

        requireActivity().onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentMyLawNoticeDetailBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getUserVMProvider())[UserVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            rvLawSubmit.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                adapter = iVAdapter
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(
                            requireContext(), R.color.transparent
                        ), 28, RecyclerView.HORIZONTAL
                    )
                )
            }

            rvLawFile.run {
                layoutManager =
                    LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
                adapter = fileTitleAdapter
                addItemDecoration(
                    MyItemDecoration(
                        ContextCompat.getColor(
                            requireContext(), R.color.transparent
                        ), 25, RecyclerView.HORIZONTAL
                    )
                )
            }
            btnNo.setOnClickListener {
                val dialog = CommonConfirmDialog.getInstance("驳回", "确定要驳回吗")
                dialog.setCancelListener(object : CommonConfirmListener {
                    override fun dOk() {
                        val map = HashMap<String, Any?>()
                        map["problemPoliceId"] = param1
                        map["refuseReason"] = ""
                        vm.lawRefuse(map)
                    }

                    override fun dCancel() {
                    }

                })
                dialog.show(parentFragmentManager, "")
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.lawRefuse.collectLatest {
                if (it) {
                    ToastUtils.show("驳回成功")
                    parentFragmentManager.popBackStack()
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.lawDetail.collectLatest { bean ->
                binding.run {
                    tvSort1.text = bean.firstTypeName
                    if (bean.thirdTypeName.isNullOrBlank()) {
                        tvSort2.text = bean.secondTypeName
                    } else {
                        tvSort2.text = bean.secondTypeName + "-${bean.thirdTypeName}"
                    }
                    edt.text = bean.problemDetail
                    iVAdapter.submitList(bean.imageList.map { lis -> lis.fileUrl })
                    fileTitleAdapter.submitList(bean.fileList)
                    val sb = StringBuilder()
                    bean.policeNameIdList.forEach {
                        sb.append(it.name)
                        sb.append("、")
                    }
                    tvZeren.text =
                        if (sb.length > 1) sb.deleteCharAt(sb.length - 1).toString() else ""
                    edtRemark.text = bean.remark
                    if (bean.rectification == 1) {
                        llDate.gone()
                        btnOk.setText("已整改")
                        btnNo.gone()
                    } else {
                        tvDate.text = bean.rectificationPeriod
                        btnOk.setText("立即整改")
                        btnOk.setOnClickListener {
                            parentFragmentManager.commit {
                                addToBackStack("team_detail")
                                replace(
                                    id, NoticeRectifyFragment.newInstance(
                                        param1!!, bean.policeNameIdList[0].id, 2
                                    ), ""
                                )
                                setReorderingAllowed(true)
                            }
                        }
                    }
                    tvFen.text = if (bean.secondType == 1) {
                        "-${bean.score}"
                    } else {
                        "${bean.score}"
                    }
                }
            }
        }
        param1?.let {
            vm.getLawDetail(it)
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: Int, param2: String) = MyLawNoticeDetailFragment().apply {
            arguments = Bundle().apply {
                putInt(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }
}